package com.xiaojianone.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.nacos.shaded.io.grpc.LoadBalancer;
import com.xiaojianone.order.bean.Order;
import com.xiaojianone.order.feign.ProductFeignClient;
import com.xiaojianone.order.service.OrderService;
import com.xiaojianone.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * ClassName  OrderServiceImpl
 * Author  XiaojianOne
 * Date  2025/3/10 10:49
 * Version  8.0
 */

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 创建订单
     * @param productId
     * @param userId
     * @return
     */
    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {

//        Product product = getProductWithLoadBalanceWithAnnotation(productId);

        Product product = productFeignClient.getProductById(productId);

        Order order = new Order();
        order.setId(userId);
        //总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(0L);
        order.setNickName("zhangsan");
        order.setAddress("beijing");
        //远程查询商品列表
        order.setProductList(Arrays.asList(product));
        return order;
    }

    /**
     * 兜底回调
     * @param productId
     * @param userId
     * @return
     */
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {

        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息"+e.getClass());
        return order;
    }

    /**
     * 基于注解的负载均衡方法
     * 获取产品
     * @param productId
     * @return
     */
    private Product getProductWithLoadBalanceWithAnnotation(Long productId) {

        String url = "http://server-product/product/"+productId;

        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

    /**
     * 负载均衡方法
     * 获取产品
     * @param productId
     * @return
     */
    private Product getProductWithLoadBalance(Long productId) {

        ServiceInstance serviceInstance = loadBalancerClient.choose("server-product");

        String url ="http://"+ serviceInstance.getHost() + ":" + serviceInstance.getPort()+"/product/"+productId;

        log.info("远程请求:{}",url);

        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }


    private Product getProduct(Long productId) {

        List<ServiceInstance> instances = discoveryClient.getInstances("server-product");

        ServiceInstance instance = instances.get(0);

        String url ="http://"+ instance.getHost() + ":" + instance.getPort()+"/product/"+productId;

        log.info("远程请求:{}",url);

        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }
}
